<template>
  <div class="store-product-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商品上架管理</span>
          <el-button type="primary" :icon="Plus" @click="showAddDialog">
            上架商品
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入商品名称、编号或型号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无商品数据"
      >
        <el-table-column label="商品图片" width="80">
          <template #default="scope">
            <el-image
              v-if="scope.row.image"
              :src="getImageUrl(scope.row.image)"
              :preview-src-list="[getImageUrl(scope.row.image)]"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 4px;"
            />
            <div v-else class="no-image">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="120" />
        <el-table-column prop="productCode" label="商品编号" width="120" />
        <el-table-column prop="model" label="型号" width="100" />
        <el-table-column prop="supplyCost" label="供货成本" width="100">
          <template #default="scope">
            ¥{{ scope.row.supplyCost }}
          </template>
        </el-table-column>
        <el-table-column prop="sellingPrice" label="销售价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.sellingPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前库存" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.currentStock > scope.row.minStock ? 'success' : 'warning'">
              {{ scope.row.currentStock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="120" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="createTime" label="上架时间" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="showEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上架/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择商品" prop="supplyProductId" v-if="!isEdit">
              <el-select 
                v-model="form.supplyProductId" 
                placeholder="请选择要上架的商品" 
                filterable
                style="width: 100%"
                @change="handleSupplyProductChange"
              >
                <el-option
                  v-for="product in availableProducts"
                  :key="product.supplyProductId"
                  :label="`${product.productName} (${product.productCode}) - 库存:${product.currentStock} - ${product.status === 1 ? '已上架' : '未上架'}`"
                  :value="product.supplyProductId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model="form.productName"
                placeholder="请输入商品名称"
                :disabled="!isEdit && !selectedSupplyProduct"
              />
            </el-form-item>
            
            <el-form-item label="商品编号" prop="productCode">
              <el-input
                v-model="form.productCode"
                placeholder="请输入商品编号"
                :disabled="isEdit || (!isEdit && !selectedSupplyProduct)"
                :readonly="isEdit"
              />
            </el-form-item>
            
            <el-form-item label="型号">
              <el-input
                v-model="form.model"
                placeholder="请输入型号"
                :disabled="isEdit || (!isEdit && !selectedSupplyProduct)"
                :readonly="isEdit"
              />
            </el-form-item>
            
            <el-form-item label="销售价格" prop="sellingPrice">
              <el-input-number
                v-model="form.sellingPrice"
                :precision="2"
                :min="0"
                style="width: 100%"
                placeholder="请输入销售价格"
              />
            </el-form-item>
            
            <el-form-item label="最低库存" v-if="!isEdit">
              <el-input-number
                v-model="form.minStock"
                :min="0"
                style="width: 100%"
                placeholder="请输入最低库存预警值"
              />
            </el-form-item>
            
            <el-form-item label="当前库存" v-if="isEdit">
              <el-input-number
                v-model="form.currentStock"
                :min="0"
                style="width: 100%"
                disabled
                readonly
              />
            </el-form-item>
            
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="商品图片">
              <el-upload
                class="image-uploader"
                :action="uploadAction"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :on-error="handleImageError"
                :before-upload="beforeImageUpload"
              >
                <img v-if="form.image" :src="getImageUrl(form.image)" class="uploaded-image" />
                <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="image-tips">
                <p>支持 jpg、png、gif 格式，文件大小不超过 5MB</p>
                <el-button v-if="form.image" @click="removeImage" type="danger" size="small" plain>删除图片</el-button>
              </div>
            </el-form-item>
            
            <el-form-item label="商品信息" v-if="selectedSupplyProduct && !isEdit">
              <div class="product-info">
                <p><strong>供货成本：</strong>¥{{ selectedSupplyProduct.supplyCost }}</p>
                <p><strong>剩余库存：</strong>{{ selectedSupplyProduct.currentStock }}</p>
                <p><strong>供应商：</strong>{{ selectedSupplyProduct.supplierName }}</p>
                <p><strong>分类：</strong>{{ selectedSupplyProduct.categoryName }}</p>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Picture } from '@element-plus/icons-vue'
import { 
  getStoreProductPage, 
  addStoreProduct, 
  updateStoreProduct, 
  deleteStoreProduct,
  updateProductStatus,
  getAvailableProductsForShelf,
  updateStoreProductFields
} from '@/api/storeProduct'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const tableData = ref([])
const availableProducts = ref([]) // 店长已进货的商品列表
const dialogVisible = ref(false)
const isEdit = ref(false)
const editId = ref(null)
const formRef = ref()

// 文件上传配置
const uploadAction = ref('/api/upload/image')
const uploadHeaders = ref({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  supplyProductId: null,
  productName: '',
  productCode: '',
  model: '',
  sellingPrice: null,
  minStock: 0,
  currentStock: 0,
  image: '',
  status: 1
})

// 选中的商品
const selectedSupplyProduct = ref(null)

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑商品' : '上架商品'
})

// 表单验证规则
const rules = {
  supplyProductId: [
    { required: true, message: '请选择要上架的商品', trigger: 'change' }
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  productCode: [
    { required: true, message: '请输入商品编号', trigger: 'blur' }
  ],
  sellingPrice: [
    { required: true, message: '请输入销售价格', trigger: 'blur' }
  ]
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  // 如果是完整URL直接返回（MinIO的URL）
  if (imagePath.startsWith('http')) {
    return imagePath
  }
  // 兼容旧的本地路径格式
  const cleanPath = imagePath.startsWith('/') ? imagePath.substring(1) : imagePath
  return `/uploads/${cleanPath}`
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    
    const response = await getStoreProductPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取店长已进货的商品列表
const getAvailableProducts = async () => {
  try {
    const response = await getAvailableProductsForShelf({
      pageNum: 1,
      pageSize: 1000, // 获取所有商品
      keyword: ''
    })
    
    if (response.code === 200) {
      availableProducts.value = response.data.records || []
    } else {
      ElMessage.error(response.message || '获取可上架商品失败')
    }
  } catch (error) {
    console.error('获取可上架商品失败:', error)
    ElMessage.error('获取可上架商品失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = null
  pagination.current = 1
  getTableData()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getTableData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  getTableData()
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  editId.value = null
  selectedSupplyProduct.value = null
  resetForm()
  getAvailableProducts()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEdit.value = true
  editId.value = row.id
  selectedSupplyProduct.value = null
  
  // 填充表单数据
  form.supplyProductId = row.supplyProductId
  form.productName = row.productName
  form.productCode = row.productCode
  form.model = row.model || ''
  form.sellingPrice = row.sellingPrice
  form.minStock = row.minStock || 0
  form.currentStock = row.currentStock || 0
  form.image = row.image || ''
  form.status = row.status
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  form.supplyProductId = null
  form.productName = ''
  form.productCode = ''
  form.model = ''
  form.sellingPrice = null
  form.minStock = 0
  form.currentStock = 0
  form.image = ''
  form.status = 1
}

// 处理供货商品选择变化
const handleSupplyProductChange = (supplyProductId) => {
  const product = availableProducts.value.find(p => p.supplyProductId === supplyProductId)
  if (product) {
    selectedSupplyProduct.value = product
    // 自动填充商品基本信息
    form.productName = product.productName
    form.productCode = product.productCode
    form.model = product.model || ''
    form.image = product.image || ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    let response
    if (isEdit.value) {
      // 编辑商品 - 只提交允许修改的字段
      const updateData = {
        productName: form.productName,
        sellingPrice: form.sellingPrice,
        image: form.image,
        status: form.status
      }
      response = await updateStoreProductFields(editId.value, updateData)
    } else {
      // 上架商品
      const submitData = {
        supplyProductId: form.supplyProductId,
        productName: form.productName,
        productCode: form.productCode,
        model: form.model,
        sellingPrice: form.sellingPrice,
        minStock: form.minStock,
        image: form.image,
        status: form.status,
        initialStock: 0 // 默认为0
      }
      response = await addStoreProduct(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '上架成功')
      dialogVisible.value = false
      getTableData()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const statusText = newStatus === 1 ? '上架' : '下架'
    
    await ElMessageBox.confirm(
      `确定要${statusText}商品"${row.productName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await updateProductStatus(row.id, newStatus)
    if (response.code === 200) {
      ElMessage.success(`${statusText}成功`)
      getTableData()
    } else {
      ElMessage.error(response.message || `${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${row.productName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteStoreProduct(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getTableData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传 JPG、PNG、GIF 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  
  return true
}

// 图片上传成功
const handleImageSuccess = (response) => {
  if (response.code === 200) {
    // MinIO返回的数据结构，使用fileUrl作为图片地址
    form.image = response.data?.fileUrl || response.data?.filePath || ''
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 图片上传失败
const handleImageError = (error) => {
  ElMessage.error('图片上传失败')
  console.error('Upload error:', error)
}

// 删除图片
const removeImage = async () => {
  if (!form.image) return
  
  try {
    // 直接传递图片路径或URL，后端会处理URL解析
    await fetch(`/api/upload/image?filePath=${encodeURIComponent(form.image)}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    form.image = ''
    ElMessage.success('图片删除成功')
  } catch (error) {
    // 即使删除失败也清空显示
    form.image = ''
    console.error('Delete image error:', error)
  }
}

// 页面挂载时加载数据
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.store-product-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.product-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  font-size: 14px;
}

.product-info p {
  margin: 5px 0;
  color: #606266;
}

.no-image {
  width: 50px;
  height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
}

.image-display {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.display-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 12px;
}

.no-image-display .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

/* 图片上传样式 */
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  display: block;
}

.uploaded-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  display: block;
}

.image-tips {
  margin-top: 8px;
}

.image-tips p {
  margin: 0;
  font-size: 12px;
  color: #909399;
}
</style>